<?php

if( !defined( 'MEDIAWIKI' ) )
die(-1);

require_once('DatabaseFunctions.php');

#install extension hook
$wgExtensionFunctions[] = "wfMostActiveUsers";


function wfMostActiveUsers(){
  global $wgRequest, $wgDBprefix, $wgOut, $wgUser, $IP, $wgUserLevels;
  $value = $wgRequest->getText( 'title' );
  $values = explode(":", $value);

  //First check if the type of content (url) is the kind to render this module (Main_Page)
  //if ($values[0] == 'Main_Page') {
  if ($value == 'Category:All') {
    $wgOut->setOrder(-80);
    $wgOut->switchBocataMode(false);
    $dbr = wfGetDB( DB_SLAVE );

    //fetch the list of users with more comments,
    $sql = "SELECT id_user, COUNT(*) as posts_count, user_name FROM ss_file_comments
    inner join mw_user on user_id = id_user GROUP BY id_user ORDER BY posts_count DESC;";
    $res = $dbr->query( $sql );
    
    
    $out .= '<div class="home_module" id="activeusers">';
    $out .= '<h2>'.wfMsg( 'most_active_users' ).'</h2><ul>';


    $count = 0;
    while ($count < 10) { //paint just first ten most active users
        
          $row = $dbr->fetchObject( $res );
          
          
          if (!is_null($row->id_user) ){  //don't paint empty things
            
            $avatar = new wAvatar( $row->id_user, 'm' );
            $user_level = new UserLevel( number_format( $user['points'] ) );
          
            //fetch the user_stats (points) rlative to one user
            $sql2 = "SELECT stats_total_points FROM mw_user_stats WHERE stats_user_id = {$row->id_user} LIMIT 1;";
            $res2 = $dbr->query( $sql2 );
            $row2 = $dbr->fetchObject( $res2 );
            
            $out .= '<li><a href="/users/'.$wgUser->whoIs($row->id_user).'">'.$avatar->getAvatarURL().'</a>&nbsp;&nbsp;';
            $out .= '<a title="'.$row->user_name.'" href="/users/'.$row->user_name.'">'.$row->user_name.'</a> <br />
            <small>('.$row->posts_count.' '.wfMsg( 'comments_posted' ).' ,'.$user_level->getLevelName();
            $out .= ' ,' . $row2->stats_total_points . ' ' . wfMsg( 'points' ) .')</small>';
	    $out .= '</li>';
            
            $dbr->freeResult( $res2 );
          }
          $count ++;
          
    }
    
    $out .= '</ul>';
    $out .= '<span><a href="/s/TopUsers">top users ranking (by points)</a></span>';
    $out .= '</div>';
    $dbr->freeResult( $res );
    $wgOut->addHtml($out);
    //$wgOut->resetOrder();
  }
}
